<?php

namespace app\api\controller;

use app\BaseController;
use think\exception\HttpResponseException;

class Base extends BaseController
{
    protected $appConfig = [];
    protected $appVersion = 0;
    protected $isCheck = 0;
    protected $app = '';
    protected $params;
    public function __construct()
    {
        header('content-Type:application/json;charset=utf-8');
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Origin:*');
        $params = input();
        if (empty($params['app_version'])) {
            $params = json_decode(file_get_contents("php://input"), true);
        }
        $isCheck = 1;
        if(!empty($params['test']) && $params['test'] == "abc123"){
            $isCheck = 0;
        }
        if($isCheck){
            $ts = $params['ts']??time();
            $sign = $params['sign']??'';
            if (empty($ts) || empty($sign)) {
                $this->error('请求错误');
            }
            if (time() - $ts > 20) {
                $this->error('请求错误2');
            }
            if (md5(substr($ts, -4)) != $sign) {
                $this->error('请求错误3');
            }
        }

        $appName = $params['app_name']??'';
        if (empty($appName)) {
            $this->error("invalid app0");
        }
        $appVersion = input('app_version', 0);
        $this->appVersion = $appVersion;
        $this->params = $params;

    }

    /**
     * 返回成功的操作
     * @param mixed $info 消息内容
     * @param mixed $data 返回数据
     * @param mixed $code 返回代码
     */
    public function success($info, $data = [],  $code = 1): void
    {
        $status = 0;
        $result = ['code' => $code, 'info' => $info, 'data' => $data, 'status' => $status];
        throw new HttpResponseException(json($result));
    }

    /**
     * 返回失败的操作
     * @param mixed $info 消息内容
     * @param mixed $data 返回数据
     * @param mixed $code 返回代码
     */
    public function error($info, $data = [], $code = 0): void
    {
        throw new HttpResponseException(json([
            'code' => $code, 'info' => $info, 'data' => $data,
        ]));
    }

    /**
     * 获取用户信息
     * @param $openid
     */
    public function getUser($appName, $uuid)
    {
        $user = [];
        if (!empty($uuid) && !empty($uuid)) {
            $user = find('xk_' . $appName . '_user', '*', ['uuid' => $uuid]);
            if (empty($user)) {
                $this->error('未识别的用户');
            }
            $user['nick_name'] = !empty($user['nick_name']) ? $user['nick_name'] : substr($user['uuid'], -8);
            $user['avatar'] = !empty($user['avatar']) ? $user['avatar'] : '/static/user.png';
        } else {
            $this->error('缺少传参111');
        }
        $this->user = $user;
    }

}
